package com.feihao.zhou.web.controller.story;

import com.feihao.zhou.bean.story.Catalog;
import com.feihao.zhou.bean.story.Company;
import com.feihao.zhou.bean.story.Question;
import com.feihao.zhou.service.story.CatalogService;
import com.feihao.zhou.service.story.CompanyService;
import com.feihao.zhou.service.story.Impl.CatalogServiceImpl;
import com.feihao.zhou.service.story.Impl.CompanyServiceImpl;
import com.feihao.zhou.service.story.QuestionService;
import com.feihao.zhou.service.story.Impl.QuestionServiceImpl;
import com.feihao.zhou.utils.BeanUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;


@WebServlet("/store/question")
public class QuestionServlet extends HttpServlet {
    static QuestionService questionService = new QuestionServiceImpl();
    static CompanyService companyService = new CompanyServiceImpl();
    static CatalogService catalogService = new CatalogServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text.html;charset=utf-8");

        //获取请求option：
        String operation = req.getParameter("operation");
        if ("list".equals(operation)) {
            //查询方法：
            findAll(req, resp);
        } else if ("toAdd".equals(operation)) {
            add(req, resp);
        } else if ("save".equals(operation)) {
            try {
                sava(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("toEdit".equals(operation)) {
            toEdit(req, resp);
        } else if ("edit".equals(operation)) {
            try {
                update(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("delete".equals(operation)) {
            delete(req, resp);
        } else if ("TestFileUpload".equals(operation)) {
            testFileUpload(req, resp);
        } else if ("testFileUpload".equals(operation)) {
            try {
                fileUpload(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("toExport".equals(operation)){
            //下载报表
            downLoadReport(req,resp);
        }
    }

    private void downLoadReport(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //设置文件打开方式
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("test.xlsx".getBytes(),"iso8859-1");
        resp.addHeader("Content-Disposition","attachment;fileName="+fileName);
        //调用业务层：
        ByteArrayOutputStream reportOs = questionService.getReport();
//        Workbook report = questionService.getReport();

        //写到前端：
//        ServletOutputStream outputStream = resp.getOutputStream();
//        report.write(outputStream);
        ServletOutputStream outputStream = resp.getOutputStream();
        reportOs.writeTo(outputStream);



    }


    private void fileUpload(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //判断操作是否支持文件上传操作：
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建文件磁盘工厂对象：
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //servlet文件上传核心对象：
            ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
            //从request中读取数据：
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            for (FileItem fileItem : fileItems) {
                //判断是否是文件：
                if (!fileItem.isFormField()) {
                    //是文件字段：写道指定位置：
                    fileItem.write(new File(req.getServletContext().getRealPath("upload"), fileItem.getName()));
                }
            }
        }
    }

    private void testFileUpload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/store/question/testFileUpload.jsp").forward(req, resp);
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        questionService.delete(id);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //重定向：
        try {
            resp.sendRedirect(req.getContextPath() + "/store/question?operation=list");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        //判断操作是否支持文件上传操作：
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建文件磁盘工厂对象：
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //servlet文件上传核心对象：
            ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
            //从request中读取数据：
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            Boolean flag = false;
            for (FileItem fileItem : fileItems) {
                if (StringUtils.isNotBlank(fileItem.getName())){
                    //有东西，则设置：
                    flag = true;
                }
            }
            //处理普通数据：
            Question question = BeanUtil.fillBean(fileItems, Question.class);
            questionService.update(question,flag);

//            System.out.println(question.getPicture());
//            System.out.println(question.getId());


            for (FileItem fileItem : fileItems) {
                System.out.println(fileItem);
                //判断是否是文件：  如果是空的也会被判断进行写操作。
                if (!fileItem.isFormField() && fileItem.getSize()!=0) {
                    //是文件字段：写道指定位置：
                    fileItem.write(new File(req.getServletContext().getRealPath("upload"), question.getId()));
                }

            }
        }

        //重定向：
            resp.sendRedirect(req.getContextPath() + "/store/question?operation=list");
    }

    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Question question = questionService.findById(id);
        req.setAttribute("question", question);

        //将所有的题目类型、所属公司加载到update页面：
        List<Catalog> catalogList = catalogService.findAll();
        List<Company> companyList = companyService.findAll();
        req.setAttribute("catalogList", catalogList);
        req.setAttribute("companyList", companyList);


        req.getRequestDispatcher(req.getContextPath() + "/WEB-INF/store/question/update.jsp").forward(req, resp);
    }


    //需要处理form表单普通数据，文件数据。
    private void sava(HttpServletRequest req, HttpServletResponse resp) throws Exception {


        //判断操作是否支持文件上传操作：
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建文件磁盘工厂对象：
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //servlet文件上传核心对象：
            ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
            //从request中读取数据：
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            boolean flag = false;
            //给定标记为，看是否有上传文件：
            for (FileItem fileItem : fileItems) {
                if (StringUtils.isNotBlank(fileItem.getName())){
                    //非空，则有东西：
                    flag = true;
                }
            }


            //处理普通数据：
            Question question = BeanUtil.fillBean(fileItems, Question.class);
            //给业务层传递标记：true则添加id，false 则不添加
            questionService.save(question,flag);
            for (FileItem fileItem : fileItems) {
//                System.out.println(fileItem);
                //判断是否是文件：    假如没有上传文件，默认是空
                if (!fileItem.isFormField() && fileItem.getSize()!=0) {
                    //是文件字段：写道指定位置：
                    fileItem.write(new File(req.getServletContext().getRealPath("upload"), question.getPicture()));
                }

            }
            //重定向：
            resp.sendRedirect(req.getContextPath() + "/store/question?operation=list");
        }
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //将所有的题目类型、所属公司加载到update页面：
        List<Catalog> catalogList = catalogService.findAll();
        List<Company> companyList = companyService.findAll();
        req.setAttribute("catalogList", catalogList);
        req.setAttribute("companyList", companyList);

        //请求转发到向到添加页面：
        req.getRequestDispatcher(req.getContextPath() + "/WEB-INF/store/question/add.jsp").forward(req, resp);

    }


    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //首先定义page,pageSize:
        int page = 1;
        int pageSize = 5;

        if (StringUtils.isNotBlank(req.getParameter("page"))) {
            page = Integer.parseInt(req.getParameter("page"));
        }

        //调用业务层方法查询所有：
        PageInfo all = questionService.findAll(page, pageSize);

        System.out.println(all);
        req.setAttribute("page", all);
        req.getRequestDispatcher("/WEB-INF/store/question/list.jsp").forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
